package com.youbug.common.config;

import com.youbug.common.exception.NoLoginException;
import com.youbug.common.exception.PasswordException;
import com.youbug.common.exception.UploadException;
import com.youbug.common.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public R<String> RuntimeExceptionHanlder(RuntimeException e){

        log.error(e.getMessage(),e);

        return R.fail(e.getMessage());
    }

    @ExceptionHandler(NoLoginException.class)
    public R<String> NoLoginExceptionHanlder(NoLoginException e){

        log.error(e.getMessage(),e);

        return R.fail(e.getMessage());
    }

    @ExceptionHandler(UploadException.class)
    public R<String> UploadExceptionHanlder(UploadException e){

        log.error(e.getMessage(),e);

        return R.fail(e.getMessage());
    }
    @ExceptionHandler(PasswordException.class)
    public R<String> UploadExceptionHanlder(PasswordException e){

        log.error(e.getMessage(),e);

        return R.fail(e.getMessage());
    }
    @ExceptionHandler(IllegalArgumentException.class)
    public R<String> IllegalArgumentExceptionHanlder(IllegalArgumentException e){

        log.error(e.getMessage(),e);

        return R.fail(e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> MethodArgumentNotValidExceptionHanlder(MethodArgumentNotValidException e){

        log.error(e.getMessage(),e);

        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (int i = 0; i < allErrors.size(); i++) {
            ObjectError objectError = allErrors.get(i);
            String defaultMessage = objectError.getDefaultMessage();

            if(i < allErrors.size() - 1 ){
                errorMsg.append(defaultMessage).append(",");
            }else{
                errorMsg.append(defaultMessage);
            }
        }
        return R.fail(errorMsg.toString());
    }
}
